package com.singleton.enumsingle;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过枚举类的方式实现单例
 */
public class Singleton_08 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //检查枚举对象是不是单例的
        Single08 instance1 = Single08.INSTANCE;
        Single08 instance2 = Single08.INSTANCE;
        System.out.println(instance1 ==instance2);
        System.out.println("instance1 hashcode :" + instance1.hashCode());
        System.out.println("instance2 hashcode :" + instance2.hashCode());

        instance1.sayOk();

        //尝试是否可破坏枚举的单例模式 创建对象的时候报错，说明反射不能破坏枚举对象单例
        Class<? extends Single08> aClass = instance1.getClass();
        Constructor<? extends Single08> declaredConstructor = aClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Single08 single08 = declaredConstructor.newInstance(); //抛异常说明无法创建单例
        System.out.println(single08.hashCode());

    }
}


/**
 * 枚举类
 */
enum Single08{

    INSTANCE ;

    public void sayOk(){
        System.out.println("OKKKKK");
    }

}